package com.study.springmvc.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.study.springmvc.dao.mapper.TeacherMapper;
import com.study.springmvc.model.Teacher;
import com.study.springmvc.model.TeacherExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/teacher")
public class TeacherController {

    @Autowired
    private TeacherMapper teacherMapper;

    @RequestMapping("/toAdd")
    public ModelAndView toAdd(ModelAndView modelAndView) {
        modelAndView.setViewName("addTeacher");
        return modelAndView;
    }

    @RequestMapping("/list")
    public ModelAndView list(@RequestParam(value = "name", required = false) String name
            , @RequestParam(value = "pageIndex", required = false) Integer pageIndex
            , @RequestParam(value = "pageSize", required = false) Integer pageSize
            , @RequestParam(value = "ageBegin", required = false) Integer ageBegin
            , @RequestParam(value = "ageEnd", required = false) Integer ageEnd
            , @RequestParam(value = "kemu", required = false) String kemu
            , ModelAndView modelAndView) {
        Integer pageNum = 1;
        if (pageIndex != null) {
            pageNum = pageIndex;
        }
        if (pageSize == null) {
            pageSize = 5;
        }

        Page<Teacher> page = PageHelper.startPage(pageNum, pageSize, true);
        TeacherExample example = new TeacherExample();
        TeacherExample.Criteria criteria  = example.createCriteria();
        if (name != null && name.trim().length() != 0) {
            criteria.andTnameLike("%" + name + "%");
        }
        if (ageBegin != null) {
            // age > 10
            criteria.andAgeGreaterThan(ageBegin);
        }
        if (ageEnd != null) {
            // age < 20
            criteria.andAgeLessThan(ageEnd);
        }

        if (kemu != null && kemu.trim().length() > 0) {
            criteria.andKemuEqualTo(kemu);
        }

        List<Teacher> teacherList = teacherMapper.selectByExample(example);
        modelAndView.addObject("teacherList", teacherList);
        modelAndView.addObject("pageIndex", pageNum);
        modelAndView.addObject("pageSize", pageSize);
        modelAndView.addObject("pageCount", page.getPages());
        modelAndView.setViewName("teacher");
        return modelAndView;
    }

}
